package alogrithm;

import java.util.ArrayList;
import java.util.Random;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/14 21:22
 */
public class GetLeastNumbers {

    Random random = new Random();

    ArrayList<Integer> arrayList = new ArrayList<>();

    public ArrayList<Integer> getLeastNumbers_Solution(int[] input, int k) {
        quickSelect(input, 0, input.length - 1, k);

        return arrayList;
    }

    private void quickSelect(int[] nums, int l, int r, int index) {
        int q = randomPartition(nums, l, r);
        if (q == index) {
            for (int i = 0; i < index; ++i) {
                arrayList.add(nums[i]);
            }
            return;
        }
        if (q < index) {
            quickSelect(nums, q + 1, r, index);
        } else {
            quickSelect(nums, l, q - 1, index);
        }
    }

    private int randomPartition(int[] nums, int l, int r) {
        int i = random.nextInt(r - l + 1) + l;
        swap(nums, i, r);
        return partition(nums, l, r);
    }

    private int partition(int[] nums, int l, int r) {
        int x = nums[r], i = l - 1;
        for (int j = l; j < r; ++j) {
            if (nums[j] <= x) {
                swap(nums, ++i, j);
            }
        }
        swap(nums, i + 1, r);
        return i + 1;
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
